import { AnyObject } from "@/types";

export class ParamsUtils {
  constructor() {}
  /** 将参数合并到url上 */
  append(url: string, params: AnyObject): string {
    let char = url.includes("?") ? "&" : "?";
    Object.keys(params).forEach((key: string) => {
      url += `${char}${key}=${params[key]}`;
      char = "&";
    });
    return url;
  }
  /**
   * 获取url上的参数
   * @param url 不传默认window.location.href
   */
  getUrlParams<T extends AnyObject>(url?: string): T {
    const params = {} as T;
    url = url || window.location.href;
    const URLParams = new URLSearchParams(url.split("?")[1]) as any;
    for (let [key, val] of URLParams.entries()) {
      Reflect.set(params, key, val);
    }
    return params;
  }
  /** 去掉url上的多余参数 */
  deleteUrlParams<T extends AnyObject>(
    url?: string,
    keys?: Array<keyof T>
  ): string {
    url = url || window.location.href;
    keys = keys && keys.length ? keys : [];
    const params = this.getUrlParams<T>(url);
    url = url.split("?")[0];
    keys.forEach((key) => {
      if (Reflect.has(params, key)) Reflect.deleteProperty(params, key);
    });
    return this.append(url, params);
  }
}

export default new ParamsUtils();
